<?php
namespace App\Http\Controllers\Api\Tg;

use Carbon\Carbon;

use App\Models\Tg\Tg;  //团购表

use App\Models\Tg\TgBill;

use App\Service\TgService;  //团购服务类

use App\Models\Bill\Bill;   //订单主表

use App\Models\Bill\BillGoods;   //订单主表

use App\Models\Tg\TgAdvert;  //团购广告位表

use App\Models\Wx\WxCustomer;  //微信会员表

use App\Models\ConfigureItems;  //自定义数据项配置表

use App\Models\Goods\GoodsStore; //商品库存表

use App\Models\ConfigureFunction; //功能配置表

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

class TgController extends Controller
{
    /**
     * 初始化拼团列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init(Request $request)
    {

        $redis_key = 'WDH_API_TG_INIT';

        //读取redis缓存，key名称：WDH_API_TG_INIT，缓存时间：1个小时
        $data = Redis::get($redis_key);
        if (!$data) {

            $data = [
                'group' => [],
                'advert' => []
            ];

            $host = $request->getSchemeAndHttpHost();

            //查询团购分组
            $data['group'] = ConfigureItems::getItems(2);

            //查询团购广告
            $advert = TgAdvert::select('photo_url' , 'link' ,'photo_type')->where(['expand_id' => 0])->get()->toArray();
            if ($advert) {
                foreach ($advert as &$ad) {
                    $data['advert'][] = [
                        'pic' => $host . $ad['photo_url'],
                    ];
                }
            }

            Redis::setex($redis_key, 3600, json_encode($data, true));

        } else {
            $data = json_decode($data, true);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $data]);

    }

    /**
     * 团购商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function search(Request $request){

        $host = $request->getSchemeAndHttpHost();
        $session_id = $request->input('session_id');
        $platform = $request->input('platform', 6);
        $group_id = $request->input('group_id', 0);
        $mall_id = $request->input('store_id');
        $init_group = $request->input('init'); //是否初始化团分组
        $limit = $request->input('limit');
        $page = $request->input('page');

        if (empty($session_id)) {
            $session_id = session_id();
            if (empty($session_id)) {
                return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
            }
        }
        if (!ebsig_is_int($group_id)) {
            $group_id = 0;
        }
        if (!ebsig_is_int($limit)) {
            $limit = 10;
        }
        if (!ebsig_is_int($page)) {
            $page = 1;
        }

        //是否开启选店
        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');
        if ( $is_open_choose_mall ) { //开启选店时mall_id不能为空
            if ( !$mall_id ) {
                $mall_id = redisTransformation(Redis::get($session_id . 'G_CHOOSE_MALL_ID'));
                if ( !$mall_id ) {
                    return response()->json([ 'code' => 10001, 'message' => '缺少参数：mall_id' ]);
                }
            }
        }

        /**
         * ==============================================
         * 获取团购分组列表
         * ==============================================
         */
        $tg_group = '';
        if ( $init_group == 1 ) {
            $tg_group = TgService::getTgGroup();
        }
        /**
         * ==============================================
         * 获取团购分组列表
         * ==============================================
         */

        /**
         * ==============================================
         * 获取团购id列表
         * ==============================================
         */
        $tg_list_redis_index = 'WDH_TG_LIST_' . $group_id;

        $tg_count = Redis::zCard($tg_list_redis_index); //检查团购数量
        if ($tg_count == 0) {

            $where = [
                ['useFlg' ,1],
                ['start_time', '<=', Carbon::now()],
                ['end_time', '>=', Carbon::now()]
            ];
            if ($group_id > 0) {
                $where[] = ['group_id' ,$group_id];
            }

            /**
             * 根据sort字段从大到小查询团购数据
             */
            $tg_list = Tg::select('tuan_id')->where($where)->orderBy('sort', 'desc')->get()->toArray();
            if ($tg_list) {
                $tg_count = 0;
                foreach ($tg_list as &$tg) {
                    Redis::zAdd($tg_list_redis_index, $tg_count, $tg['tuan_id']);
                    $tg_count++;
                }
                Redis::expire($tg_list_redis_index, 7200); //设置过期时间为2小时
            }

        }
        if ($tg_count == 0) {
            return response()->json([ 'code' => 10002, 'message' => '没有团购数据' ]);
        }

        //从小到大分页获取团购id
        $tg_list = Redis::zRange($tg_list_redis_index, ($page-1) * $limit, $page * $limit - 1);
        if (!$tg_list) {
            return response()->json([ 'code' => 10002, 'message' => '没有团购数据' ]);
        }
        /**
         * ==============================================
         * 获取团购id列表
         * ==============================================
         */

        //是否开启门店选品
        $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');

        //获取客户号
        $pcustID = get_customer_id($session_id, $platform);

        $return_data = [];

        if ($tg_list) {

            foreach ( $tg_list as &$id ) {

                //获取redis缓存的团购详情信息
                $tg_cache = TgService::getCache($id);
                if ( !$tg_cache ) {
                    continue;
                }

                $status = 1; //0:已售罄 1:可售卖 2:已参团

                /**
                 * 已开启门店选店
                 * 团购结算为指定门店生效
                 * 检查当前团购活动是否包含当前传参的门店id
                 * 如果没有当前门店，则团购改为“已售罄”
                 */
                if ( $is_open_choose_mall) {

                    //门店范围类型mall_range_type  0、无门店 1、全部 2、指定
                    if (isset($tg_cache['config']['mall_range_type']) && $tg_cache['config']['mall_range_type'] == 2) {
                        if (!in_array($mall_id, $tg_cache['activity_mall'])) {
                            $status = 0;
                        }
                    }

                }

                //检查会员是否已开团或拼团，且未拼团成功
                $parent_order_no = ''; //拼团主单号
                $order_no = ''; //拼团主单号
                if ($pcustID) {
                    $order = TgService::getCustomerTgOrder($id, $pcustID);
                    if ($order) {
                        $status = 2;
                        $parent_order_no = $order['parent_bill_no'];
                        $order_no = $order['bill_no'];
                    }
                }

                /**
                 * 团购活动状态为“可售卖”时或者是“已参团”
                 * 查询商品库存，并检查商品销售数和限购数
                 */
                $sale_price = 0; //商品销售价
                if ( $status == 1 || $status == 2 ) {

                    if (empty($tg_cache['goods'])) {
                        $status = 0;
                    } else {

                        $enableSaleAmount = 0;
                        $total_tuan_store = 0; //团购总库存数
                        $total_buy_count = 0; //团购总销售数
                        foreach ( $tg_cache['goods'] as &$goods ) {

                            if ($goods['salePrice'] > $sale_price) {
                                $sale_price = $goods['salePrice'];
                            }

                            $total_tuan_store += $goods['tuan_store'];
                            $total_buy_count += TgService::getTgGoodsBuyNum($id, $goods['postID']);

                            //检查库存
                            if ( $is_choose_goods_by_mall ) {
                                $enableSaleAmount += GoodsStore::search($goods['product_code'], $goods['product_spec'], $mall_id);
                            } else {
                                $enableSaleAmount += GoodsStore::search($goods['product_code'], $goods['product_spec']);
                            }

                        }

                        if ($enableSaleAmount <= 0 || $total_tuan_store <= $total_buy_count) {
                            $status = 0;
                        }

                    }

                }

                $return_data[] = [
                    'id' => app_to_int($id),
                    'name' => $tg_cache['goodsName'],
                    'brief' => app_to_string($tg_cache['goods_brief']),
                    'sale_price' => app_to_decimal($sale_price),
                    'price' => app_to_decimal($tg_cache['price']),
                    'pic' => $host . $tg_cache['goods_photo_link'],
                    'success_num' => app_to_int($tg_cache['success_tuan_num']),
                    'sale_num' => app_to_int($tg_cache['show_buy_count'] + TgService::getTgBuyNum($id)),
                    'status' => $status,
                    'bill_no' => app_to_string($order_no),
                    'parent_order_no' => app_to_string($parent_order_no)
                ];

            }

        }

        $data = [
            'page' => app_to_int($page),
            'limit' => app_to_int($limit),
            'count' => $tg_count,
            'group' => !empty ( $tg_group['group'] ) ? $tg_group['group'] : '' ,  //分组
            'advert' => !empty ( $tg_group['advert'] ) ? $tg_group['advert'] : '' ,  //广告
            'list' => $return_data
        ];

        //
        if ( $init_group == 0 ) {
            unset($data['group']);
            unset($data['advert']);
        }

        return response()->json([
            'code' => 200 ,
            'message' => 'ok',
            'data' =>$data
        ]);

    }



    /**
     * 团购详情
     * @param Request $request
     * @return array
     */
    public function detail(  Request $request  )
    {

        $host = $request->getSchemeAndHttpHost();
        $id = $request->input('id');
        $mall_id = $request->input('store_id');
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id');
        $datetime = Carbon::now();

        if ( !ebsig_is_int($id) ) {
            return response()->json([ 'code' => 100001 , 'message' => '缺少参数：id' ]);
        }

        if (empty($session_id)) {
            $session_id = session_id();
            if (empty($session_id)) {
                return response()->json([ 'code' => 100002 , 'message' => '缺少参数：session_id' ]);
            }
        }

        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall'); //是否开启选店
        if ( $is_open_choose_mall ) {
            if ( !$mall_id ) {
                $mall_id = redisTransformation(Redis::get($session_id . 'G_CHOOSE_MALL_ID'));
                if ( !$mall_id ) {
                    return response()->json([ 'code' => 100003, 'message' => '缺少参数：mall_id' ]);
                }
            }
        }

        //查询团购信息
        $tg = TgService::getCache($id);
        if ( empty($tg) || $tg['useFlg'] == 0 ) {
            return response()->json([ 'code' => 100004 , 'message' => '活动已结束' ]);
        }

        //是否开启门店选品
        $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');


        $status = 3; //状态 1、活动未开始 2、活动已开始 3、活动已结束 4、有未成团的订单 5、超出用户可购买最大数量 6、不在该门店销售
        $tg_bill_status = 0; //团购订单状态，$status=4时检查该字段 0、未付款 1、已付款，未成团
        /**
         * 团购订单号
         * $status=4，$tg_bill_status=0时返回拼团订单号，$tg_bill_status=1时返回拼团主订单号
         * $status=5,返回拼团主订单号
         */
        $bill_no = '';
        $count_down = 0; //倒计时


        /**
         * ========================================
         * 团购活动状态
         * ========================================
         */
        if ( $tg['start_time'] > $datetime ) {  //活动未开始
            $status = 1;
            $count_down = strtotime( $tg['start_time']);
        } else if ( $tg['end_time'] > $datetime ) {  //活动已开始
            $status = 2;
            $count_down = strtotime( $tg['end_time'] );
        }

        //判断选择的门店在不在选店范围内
        if (isset($tg['activity_mall']) && !empty($tg['activity_mall'])) {
            if (!in_array($mall_id, $tg['activity_mall'])) {
                $status = 6;
            }
        }


        /**
         * ========================================
         * 凑团数据
         * =========================================
         */
        $pt_wct_bill = [];//凑团订单数组
        if ( $tg['tuan_type'] == 1 && $tg['show_open_tuan_num'] > 0 ) {

            //获取正在未成团的拼团订单数据
            $pt_wct_keys = Redis::keys('TG_BILL_LIST_'. $id . '_*');

            if ( $pt_wct_keys ) {

                foreach ( $pt_wct_keys as &$key ) {

                    //已满足显示凑团数量，循环结束
                    if (count($pt_wct_bill) == $tg['show_open_tuan_num']) {
                        break;
                    }

                    $redis_bill_data = Redis::sMembers($key); //获取对应键值的参团订单信息
                    $bill_num  = Redis::scard($key); //已参团人数
                    $lack_num = $tg['success_tuan_num'] - $bill_num; //需参数人数 - 已参团人数 = 剩余参团人数

                    foreach ( $redis_bill_data as &$bill ) {

                        $json_bill = json_decode( $bill ,true);

                        //只查询拼团主订单，非主单跳过
                        if ( $json_bill['bill_no'] == $json_bill['parent_bill_no'] ) {
                            continue;
                        }

                        //查询主订单
                        $temp_bill = Bill::select('pcustID', 'deliver_name', 'deliver_province')->find($json_bill['bill_no']);
                        if (!$temp_bill) {
                            continue;
                        }

                        //查找粉丝头像
                        $wx_customer = WxCustomer::getCache($temp_bill->pcustID);

                        //查找粉丝头像
                        if (!empty($wx_customer)) {
                            $head_pic = $wx_customer['headPic'];
                        } else {
                            $head_pic = $host . '/static/images/m/tuan/tuan2.png';
                        }

                        $pt_wct_bill[] = [
                            'deliver_name' => app_to_string($temp_bill->deliver_name),
                            'deliver_province' => app_to_string($temp_bill->deliver_province),
                            'head_pic' => $head_pic,
                            'lack_num' => $lack_num,
                            'bill_no' => app_to_string($json_bill['parent_bill_no'])
                        ];

                    }

                }

            } else {

                $field = [
                    'pcustID','bill_status','bill_no','parent_bill_no','deliver_name','deliver_province'
                ];
                $pt_bill_data = TgBill::select($field)->where([
                    ['bill_status' ,'=', 1],
                    ['promotion_id' ,'=', $id]
                ])
                    ->whereRaw('bill_no=parent_bill_no')
                    ->orderBy('bill_no','DESC')
                    ->paginate( $tg['show_open_tuan_num'] )
                    ->toArray();

                if ( !empty( $pt_bill_data ['data']) ) {

                    foreach ( $pt_bill_data['data'] as $bill ) {


                        //查询该主单下的订单数量
                        $tg_bill_num = TgBill::where([
                            'parent_bill_no' => $bill['parent_bill_no'],
                            'bill_status'=>1,
                        ])->orWhere([
                            'parent_bill_no' => $bill['parent_bill_no'],
                            'bill_status'=>4,
                        ])->count('bill_no');

                        $wx_customer = WxCustomer::getCache($bill['pcustID']);

                        //查找粉丝头像
                        if (!empty($wx_customer)) {
                            $head_pic = $wx_customer['headPic'];
                        } else {
                            $head_pic = $host . '/static/images/m/tuan/tuan2.png';
                        }

                        $pt_wct_bill[] = [
                            'deliver_name' => app_to_string($bill['deliver_name']),
                            'deliver_province' => app_to_string($bill['deliver_province']),
                            'head_pic' => $head_pic,
                            'lack_num' => $tg['success_tuan_num'] - $tg_bill_num,  //剩余参团人数 = 团购数-已参团人数
                            'bill_no' => app_to_string($bill['parent_bill_no'])
                        ];
                    }
                }
            }

        }


        /**
         * =======================
         * 判断会员是否已经参团
         * ======================
         */

        //用户可购买数量，为0时表示不限购
        $user_can_buy_num = $tg['user_can_buy_num'];

        //获取会员号
        $pcustID = get_customer_id($session_id, $platform);

        if ( $pcustID ) {

            //查询当前会员参团的订单信息
            $customer_tg_bill = Bill::select('bill_status', 'pay_status', 'bill_no','billType', 'parent_bill_no')
                ->where(['pcustID' => $pcustID, 'activity_id' => $id ])
                ->orderBy('bill_no', 'desc')
                ->get()->toArray();
            if ( $customer_tg_bill ) {

                if ( $customer_tg_bill[0]['bill_status'] == 0 ) {

                    $status = 4;   //查看团详情

                    if ( $customer_tg_bill[0]['pay_status'] == 0 ) {    //未付款
                        $bill_no = $customer_tg_bill[0]['bill_no'];
                    } else  {      //已付款、团未成功
                        $bill_no = $customer_tg_bill[0]['parent_bill_no'];
                        $tg_bill_status = 1;
                    }

                } else if ( $user_can_buy_num > 0 ) {   //如果开启限购，则查询会员已经参与购买的次数

                    $total_buy_amount = 0; //会员已购买数量
                    foreach ($customer_tg_bill as &$tg_bill) {
                        if ($tg_bill['bill_status'] == 5 || $tg_bill['billType'] != 9) {
                            continue;
                        }
                        $buy_amount = BillGoods::where('bill_no', $tg_bill['bill_no'])->sum('goods_amount');
                        $total_buy_amount += $buy_amount;
                    }

                    $user_can_buy_num -= $total_buy_amount;
                    $user_can_buy_num = $user_can_buy_num < 0 ? 0 : $user_can_buy_num;
                    if ( $user_can_buy_num <= 0 ) {
                        $status = 5;
                        $bill_no = $customer_tg_bill[0]['parent_bill_no'];
                    }

                }

            }

        }

        //获取不同规格组合的商品信息
        $goods_list = [];

        $tg_goods = $tg['goods'];
        if  ( empty($tg_goods) ) {
            return response()->json([ 'code' => 100005 , 'message' => '团购商品错误']);
        }

        foreach ( $tg_goods as &$g ) {

            //检查库存
            if ( $is_choose_goods_by_mall ) {
                $enableSaleAmount = GoodsStore::search($g['product_code'], $g['product_spec'], $mall_id);
            } else {
                $enableSaleAmount = GoodsStore::search($g['product_code'], $g['product_spec']);
            }

            //已经购买的商品数量
            $goods_buy_num = TgService::getTgGoodsBuyNum($id, $g['postID']);

            //可购买数量 = 限制购买数量 - 已购买数量
            $can_buy_num = $g['tuan_store'] - $goods_buy_num;
            if ($can_buy_num < 0) {
                $can_buy_num = 0;
            }

            if ($enableSaleAmount == 0 || $can_buy_num == 0) {
                $store = 0;
            } else if ($enableSaleAmount > $can_buy_num) {
                $store = $can_buy_num;
            } else {
                $store = $enableSaleAmount;
            }
            if ( $user_can_buy_num > 0 && $user_can_buy_num < $store) {
                $store = $user_can_buy_num;
            }

            //规格key，多个规格id连接起来
            $temp_goods_spec_id = explode(',', $g['specID']);
            $spec_key = '';
            foreach ($temp_goods_spec_id as &$spec_id) {
                if (!empty($spec_id)) {
                    $spec_key .= $spec_id;
                }
            }
            if (empty($spec_key)) {
                $spec_key = 0;
            }

            $goods_list[$spec_key] = [
                'id' => app_to_int($g['postID']),
                'sale_price' => app_to_decimal($g['salePrice']),
                'price' => app_to_decimal($g['tuan_price']),
                'enable_sale_amount' => app_to_int($store),
                'img_link' => $g['img_link'],
            ];

        }

        //查询商品评论信息
        $comments = TgService::getTgGoodsComments( $tg['mainPostID'],$pcustID );

        //团购的购买数量
        $tg_buy_num = TgService::getTgBuyNum($id);

        $return_data = [
            'code' => 200,
            'message'=>'ok',
            'data' => [
                'id' => app_to_int($id),
                'post_id' => app_to_int($tg['postID']),
                'main_post_id' => app_to_int($tg['mainPostID']),
                'tg_type' =>  app_to_int($tg['tuan_type']),
                'status' => $status,
                'count_down' => $count_down,
                'tg_bill_status' => $tg_bill_status,
                'bill_no' => app_to_string($bill_no),
                'goods_name' => $tg['goodsName'],
                'sale_price' => app_to_decimal($tg['salePrice']),
                'price' => app_to_decimal($tg['price']),
                'brief' => app_to_string($tg['goods_brief']),
                'button_content' => app_to_string($tg['button_content']),
                'sale_num' => app_to_int($tg['show_buy_count'] + $tg_buy_num),
                'success_tuan_num' => app_to_int($tg['success_tuan_num']),
                'user_can_buy_num' =>  app_to_int($tg['user_can_buy_num']),
                'goods_description' => app_to_string($tg['goods_description']),
                'other_tuan' => $pt_wct_bill,
                'goods_pic' => $tg['goods_pic'],
                'goods_list' => $goods_list,
                'goods_spec' => !empty ( $tg['goods_spec'] ) ? $tg['goods_spec'] : '',
                'goods_comments' => $comments
            ]
        ];

        return response()->json($return_data);

    }

    /**
     * ================================
     * 参团页数据
     * @param Request $request
     */
    public function participate( Request $request )
    {

        $host = $request->getSchemeAndHttpHost();
        $bill_no = $request->input('id');  //主订单号
        $mall_id = $request->input('mall_id');
        $session_id = $request->input('session_id');
        $platform = $request->input('platform',6);

        if (empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '订单号不能为空']);
        }

        if (empty($session_id)) {
            $session_id = session_id();
            if (empty( $session_id ) ) {
                return response()->json(['code' => 100002, 'message' => '缺少参数：session_id']);
            }
        }

        //是否开启选店
        $is_open_choose_mall = 0;

        //是否开启门店选品
        $is_choose_goods_by_mall = 0;

        $mall_setting = ConfigureFunction::getConfigure(8);
        if (!empty($mall_setting) ) {
            if( isset( $mall_setting['is_open_choose_mall'] ) && !empty( $mall_setting['is_open_choose_mall'] ) ) {
                $is_open_choose_mall = $mall_setting['is_open_choose_mall'];
            }
            if( isset( $mall_setting['is_choose_goods_by_mall'] ) && !empty( $mall_setting['is_choose_goods_by_mall'] ) ) {
                $is_choose_goods_by_mall = $mall_setting['is_choose_goods_by_mall'];
            }
        }

        if ( $is_open_choose_mall ) {
            if ( !$mall_id ) {
                $mall_id = redisTransformation(Redis::get($session_id . 'G_CHOOSE_MALL_ID'));
                if ( !$mall_id ) {
                    return response()->json([ 'code' => 100003, 'message' => '缺少参数：mall_id' ]);
                }
            }
        }

        //查询订单信息
        $tg_bill_data = Bill::find($bill_no);
        if (!$tg_bill_data) {
            return response()->json(['code' => 100004, 'message' => '订单信息不存在']);
        }

        $id= $tg_bill_data['activity_id'];

        //查询团购信息
        $tg =TgService::getCache($id);

        if ( !$tg || $tg['useFlg'] == 0 ) {
            return response()->json(['code' => 100005, 'message' => '团购活动不存在']);
        }

        //获取会员号
        $pcustID = get_customer_id( $session_id, $platform );

        //分享页进入并判断该用户是否已经开过团或参过团
        $customer_pt_bill =json_decode(Redis::get('G_WDH_CUSTOMER_TG_' . $id . '_' . $pcustID),true);

        if ( $customer_pt_bill ) {
            $customer_bill = $customer_pt_bill;
        } else {
            $customer_bill = Bill::select('bill_no', 'bill_status', 'parent_bill_no')
                ->where([
                    ['pcustID', '=', $pcustID],
                    ['activity_id', '=', $id],
                    ['bill_status', '=', 0],
                ])
                ->orderBy('bill_no', 'DESC')
                ->first();
        }

        $is_location_order = 0;   //是否要调整到订单详情页   0.否 1.是    //如果未支付要跳转订单详情页
        $is_location_participate = 0;  //是否要跳转到参团页   0.否 1.是   //点击分享或者参团的订单，如果传过来的订单号，不是自己的主订单号，则跳转到自己的参团结果页
        $parent_bill_no = (string)$bill_no;  //主团订单号  //点击分享或者参团的订单，如果传过来的订单号，不是自己的主订单号，则主单号则是自己的主单号，然后跳转到自己的参团结果页
        $customer_bill_no = '';  //参团人订单号

        if ( $customer_bill ) {

            //如果未支付要跳转订单详情页
            if ($customer_bill['bill_status'] == 0) {
                $is_location_order = 1;
                $customer_bill_no =  (string)$customer_bill['bill_no'];  //参团人的订单号，用于跳转订单详情页
            }

            //点击分享或者参团的订单，如果传过来的订单号，不是自己的主订单号，则跳转到自己的参团结果页
            if ( $customer_bill['parent_bill_no'] != $bill_no ) {
                $is_location_participate = 1;
                $parent_bill_no =  (string)$customer_bill['parent_bill_no'];
            }
        }

        $is_activity_mall = 1; //是否是活动门店
        if ( $is_open_choose_mall == 1 ) {
            //判断选择的门店在不在选店范围内
            if (isset($tg['activity_mall']) && !empty($tg['activity_mall'])) {
                if (!in_array($mall_id, $tg['activity_mall'])) {
                    $is_activity_mall = 0;
                }
            }
        }

        //团活动状态  0、已过期 1、进行中
        $time_status = 1;
        $end_time = strtotime($tg_bill_data['createTime'] . ' +24 hour') * 1000;
        if ($end_time < date('Y-m-d H:i:s')) {
            $time_status = 0;
        }

        $tg_status = 1;   //默认是1    //1、开团成功  2、参团成功 3、未参团 4、(未参团)组团成功，5.组团成功，6.组团失败
        $tg_user_number = $tg['success_tuan_num'];  //几人团

        /**
         * ==========================
         *获取参团人列表信息
         * ==========================
         */
        $pt_cust_data = [];

        $tg_bill_list = Redis::sMembers('TG_BILL_LIST_' . $id . '_' . $bill_no);

        $bill_info_from = 'redis';

        if ( $tg_bill_list ) {

            foreach ($tg_bill_list as $tg_bill) {
                $pt_cust_data[] =  json_decode($tg_bill,true);
            }
            sort($pt_cust_data);

        } else {

            $bill_info_from = 'db';

            $pt_cust_data = Bill::select('createTime', 'pcustID', 'bill_status', 'bill_no')
                ->where([
                    ['parent_bill_no', '=', $bill_no],
                    ['activity_id', '=', $id],
                    ['pay_status', '=', 1],
                ])
                ->orderBy('bill_no', 'ASC')
                ->get()
                ->toArray();

        }

        $tg_person_num = 0; //查询该团已参团人数

        $bill_data = [];  //参团人订单信息

        $cust_tuan_list = [];  //参团人信息

        if ( !empty( $pt_cust_data ) ) {

            foreach ($pt_cust_data as &$item) {

                $tg_person_num++;

                //获取当前登录者的订单信息
                if ($pcustID == $item['pcustID']) {
                    $bill_data = [
                        'bill_no' => $item['bill_no'],
                        'bill_status' => isset( $item['bill_status'] ) ? $item['bill_status'] : 0
                    ];
                }

                $wx_customer = WxCustomer::getCache($item['pcustID']);

                //查找粉丝头像
                $nick_name = '';
                if (!empty($wx_customer)) {
                    $head_pic = $wx_customer['headPic'];
                    $nick_name = !empty( $wx_customer['nickName'] ) ? $wx_customer['nickName'] :'';
                } else {
                    $head_pic = $host . '/static/images/m/tuan/tuan2.png';
                }

                $cust_tuan_list[] = [
                    'head_pic' => $head_pic,
                    'nick_name' => $nick_name,
                    'bill_time' => $item['createTime']
                ];
            }

        }

        //剩余参团人数  团购人数-已参团人数
        $left_user_number = $tg_user_number - $tg_person_num;

        if (!empty( $bill_data ) ) {//参过团

            $customer_bill_no = (string)$bill_data['bill_no'];

            if ( $bill_no != $bill_data['bill_no'] ) {//不是团长

                if ( $bill_data['bill_status'] == 1 ) {
                    $tg_status  = 4;  //成团
                }

                if ( $bill_info_from == 'redis' || $bill_data['bill_status'] == 0 ) {
                    $tg_status = 2;  //还差几人成团
                }
            }

            if ( $bill_data['bill_status'] == 1 ) {
                $tg_status  = 5;  //再开团
            } else if ( $bill_data['bill_status'] == 5 ) {
                $tg_status = 6;  //组团失败
                if ( $left_user_number == 0 || $tg['is_open_mt'] == 1 ) {  //剩余参团人数为0或开启模拟成团
                    $tg_status = 5;  //再开团
                }
            }

        } else {//未参团
            $tg_status = 3;   //我也要参团
            if ( $tg_bill_data['bill_status'] == 1 ) {
                $tg_status = 4;  //我也要开团
            } else if ( $tg_bill_data['bill_status'] == 5 ) {
                $tg_status = 6;  //组团失败
                if ( $left_user_number  == 0 || $tg['is_open_mt'] == 1 ) {
                    $tg_status = 4; //(未参团)组团成功
                }
            }
        }

        /**
         * ==========================
         * 查询会员已购买数量
         * -=========================
         */
        $overbuy  = 0;    //用户可购买是否已超出限购数量

        $user_can_buy_num = $tg['user_can_buy_num'];  //用户可购买数量，为0表示不限购

        //如果团购状态是 3、未参团 4、(未参团)组团成功，5.组团成成功  并且 开启了限购
        if (( $tg_status == 3 || $tg_status == 4 || $tg_status == 5 ) && $user_can_buy_num > 0 ) {

            $customer_buy_amount = Bill::join("bill_goods","bill_master.bill_no",'=','bill_goods.bill_no')
                ->where([
                    ['bill_master.pcustID', '=', $pcustID],
                    ['bill_master.billType', '=', 9],
                    ['bill_master.bill_status', '<>', 5],
                    ['bill_master.activity_id', '=', $id],
                ])
                ->sum('bill_goods.goods_amount');

            if ( $customer_buy_amount > 0 ) {
                $user_can_buy_num -= $customer_buy_amount;
                $user_can_buy_num = $user_can_buy_num < 0 ? 0 : $user_can_buy_num;
                if ( $user_can_buy_num <= 0) {
                    $overbuy = 1;     //用户可购买已超出限购数量
                }
            }
        }

        /**
         * ================
         * 针对于模拟成团
         * ================
         */
        //如果组团成功 或者 组团失败  并且开启了模拟成团
        if (( $tg_status == 4 || $tg_status == 5) && $tg['is_open_mt'] == 1 ) {
            $mt_num = $left_user_number;
            $left_user_number  = 0;
            for ( $i = 0; $i < $mt_num; $i++ ) {
                $bill_time = date("Y-m-d H:i:s", strtotime($bill_data['createTime'] . " +1 hour"));
                if ($bill_time > $tg['end_time']) {
                    $bill_time = $tg['end_time'];
                }
                $cust_tuan_list[] = [
                    'head_pic' =>  $host . '/static/images/m/tuan/tuan2.png',
                    'nick_name' => '匿名',
                    'bill_time' => $bill_time
                ];
            }
        }

        //获取不同规格组合的商品信息
        $goods_list = [];
        $goods_sale_list = $tg['goods'];

        foreach ($goods_sale_list as &$g) {

            //检查库存
            if ($is_choose_goods_by_mall) {
                $enableSaleAmount = GoodsStore::search($g['product_code'], $g['product_spec'], $mall_id);
            } else {
                $enableSaleAmount = GoodsStore::search($g['product_code'], $g['product_spec']);
            }

            //已经购买的商品数量
            $goods_buy_num = TgService::getTgGoodsBuyNum($id,$g['postID']);

            //可购买数量 = 限制购买数量 - 已购买数量
            $can_buy_num = $g['tuan_store'] - $goods_buy_num;
            if ( $can_buy_num < 0 ) {
                $can_buy_num = 0;
            }

            if ( $enableSaleAmount == 0 || $can_buy_num == 0 ) {
                $store = 0;
            } else if ( $enableSaleAmount > $can_buy_num ) {
                $store = $can_buy_num;
            } else {
                $store = $enableSaleAmount;
            }
            if ( $user_can_buy_num > 0 && $user_can_buy_num < $store) {
                $store = $user_can_buy_num;
            }

            $temp_goods_spec_id = explode(',', $g['specID']);
            $spec_key = '';
            foreach ($temp_goods_spec_id as &$id) {
                if (!empty($id)) {
                    $spec_key .= $id;
                }
            }
            if (empty($spec_key)) {
                $spec_key = 0;
            }

            $goods_list[$spec_key] = [
                'id' => $g['postID'],
                'sale_price' => $g['salePrice'],
                'price' => $g['tuan_price'],
                'enable_sale_amount' => $store,
                'img_link' => $g['img_link'],
            ];
        }

        $return_data = [
            'code' => 200,
            'message' =>'ok',
            'data' => [
                'id' => app_to_int($tg['tuan_id']),  //团购活动ID
                'price' => app_to_decimal($tg['price']),  //团购价格
                'goods_name' => $tg['goodsName'],  //团购商品名称
                'goods_photo_link' => $host . $tg['goods_photo_link'],
                'user_can_buy_num' => app_to_int($user_can_buy_num),  //用户可购买数量
                'is_location_order' => $is_location_order,
                'is_location_participate' => $is_location_participate,
                'customer_bill_no' => app_to_string( $customer_bill_no ),
                'parent_bill_no' => app_to_string($parent_bill_no ),
                'is_activity_mall' => $is_activity_mall,  //是否是活动门店
                'time_status' => $time_status, //活动状态
                'end_time' => $end_time,
                'tg_status' => $tg_status,  //团购状态
                'tg_user_number' => app_to_int( $tg_user_number ),  //几人团
                'left_user_number' => app_to_int( $left_user_number ),  //剩余参团人数
                'cust_tuan_list' => $cust_tuan_list,  //参团人信息
                'overbuy' => $overbuy,  //是否超过 用户购买数量
                'spec' => $tg['goods_spec'],  ///商品规格
                'list' =>$goods_list  //商品信息
            ]
        ];


        return  $return_data;

    }

}